<?php

declare (strict_types=1);
/**
 * @copyright 深圳市易果网络科技有限公司
 * @version 1.0.0
 * @link https://dayiguo.com
 */
namespace App\Common;

use App\Exception\BusinessException;

use Hyperf\AsyncQueue\Driver\DriverFactory;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Guzzle\ClientFactory AS GuzzleClientFactory;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Utils\Context;

use Psr\Container\ContainerInterface;
use Psr\EventDispatcher\EventDispatcherInterface;
use Psr\Log\LoggerInterface;

/**
 * 基类
 *
 * @author 刘兴永(aile8880@qq.com)
 * @package App\Common
 */
abstract class CommonAbstract
{
    /**
     * 容器
     *
     * @Inject
     * @var ContainerInterface
     */
    protected $container;

    /**
     * 请求类
     *
     * @Inject
     * @var RequestInterface
     */
    protected $request;

    /**
     * 响应类
     *
     * @Inject
     * @var ResponseInterface
     */
    protected $response;

    /**
     * Guzzle 协程客户端
     *
     * @Inject
     * @var GuzzleClientFactory
     */
    protected $guzzle;

    /**
     * @Inject
     * @var EventDispatcherInterface
     */
    protected $dispatcher;

    /**
     * redis
     *
     * @Inject
     * @var \Redis
     */
    protected $redis;

    /**
     * @var DriverFactory
     */
    protected $driver;

    /**
     * CommonAbstract constructor.
     *
     * @param DriverFactory $driverFactory
     */
    public function __construct(DriverFactory $driverFactory)
    {
        $this->driver = $driverFactory->get('default');
    }

    /**
     * 日志管理
     *
     * @param $channel
     * @return mixed
     */
    protected function logger($channel): LoggerInterface
    {
        return $this->container->get(LoggerFactory::class)->get('log', $channel);
    }

    /**
     * 成功响应
     *
     * @param mixed $data 返回数据&提示内容
     * @return mixed
     */
    protected function success($data = [])
    {
        // 将响应数据存储至上下文
        Context::set('successful_data', $data);

        throw new BusinessException(200, 'success');
    }

    /**
     * 错误响应
     *
     * @param string $message 提示内容
     * @param array $placeholder
     * @return mixed
     */
    protected function error(string $message = 'COMMON.HANDLE_FAILED', array $placeholder = [])
    {
        // 国际化支持
        $message = str_replace('api.', '', __('api.' . $message, $placeholder));

        throw new BusinessException(400, $message);
    }
}